package com.gxa.util;

import com.gxa.exception.SystemException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UploadUtil {


    /**
     * 单文件上传
     * @param multipartFile
     * @param allowExts
     * @param uploadPath
     * @throws IOException
     */
    public static String uploadFile(MultipartFile multipartFile, String allowExts,String uploadPath) throws IOException {
        // 获取文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        if (!StringUtil.checkExt(allowExts, StringUtil.getExt(originalFilename))) {
            throw new SystemException(1001,"只允许上传："+allowExts);
        }
        //生成新的文件名
        String newFileName = uniqueName(originalFilename);

        // 生成一个时间的文件夹  /2021/01/28
        String datePath = StringUtil.getDatePath();

        uploadPath = uploadPath+datePath;
        StringUtil.createDirs(uploadPath);
        // 文件抽象
        File saveFile = new File(uploadPath, newFileName);
        // 上传
        multipartFile.transferTo(saveFile);
        return newFileName;
    }

    /**
     * 多文件上传
     * @param multipartFiles
     * @param allowExts
     * @param uploadPath
     * @throws IOException
     */
    public static List<String> uploadFiles(MultipartFile[] multipartFiles, String allowExts, String uploadPath) throws IOException {
        ArrayList<String> updateFiles = new ArrayList<>();
        //遍历
        for (MultipartFile multipartFile : multipartFiles) {
            String uploadFile = uploadFile(multipartFile, allowExts, uploadPath);
            updateFiles.add(uploadFile);
        }
        return updateFiles;
    }


    /**
     * 生成唯一的文件名
     * @param fileName
     * @return
     */
    private static String uniqueName(String fileName){
        // 重新生成一个当前系统中唯一的文件名
        String uid = UUIDUtil.getUid();
        String newFileName = uid+"."+ StringUtil.getExt(fileName);
        return newFileName;
    }

}
